import { View, Text, Image, Map, Picker, Input } from '@tarojs/components'
import Taro, { useDidShow, useLoad } from '@tarojs/taro'
import { useState } from 'react'
import axios from '@/request/index'
import './index.scss'

export default function Index() {

  const [location, setLocation] = useState('广州市从化区');
  const [areaList, setAreaList] = useState([]);
  const [cityMap, setCityMap] = useState([]);
  const [selectArea, setSelectArea] = useState(0);
  const [longitude, setLongitude] = useState(113.678280);
  const [latitude, setLatitude] = useState(23.628439);
  const [visible, setVisible] = useState(false);
  const [detailVisible, setDetailVisible] = useState(false);
  const [detail, setDetail] = useState<any>();
  const [comment, setComment] = useState<any>('');

  const [list, setList] = useState<any[]>([]);

  useLoad(() => {
    console.log('Page loaded.');
  })

  const initLocation = async () => {
    const res = await axios.get('/city/cityMap')
    if (res && res.data) {
      const arr = [];
      res.data.map((item) => {
        if (item.cityVOS) {
          item.cityVOS.map(subItem => {
            if (subItem.districts) {
              subItem.districts.map(districtItem => {
                // @ts-ignore
                arr.push(`${item.name}-${subItem.name}-${districtItem.district}`) 
              })
            }
          })
        }
      })
      const firstLon = res.data[0].cityVOS[0].districts[0].lon;
      const firstLa = res.data[0].cityVOS[0].districts[0].la;
      // await initHospital(firstLon, firstLa);
      if (arr.length) {
        setLocation((arr[0] + '').split('-').join(' '));
      }
      setAreaList(arr);
      setCityMap(res.data);
    }
  }
  
  useDidShow(async () => {
    // // initLocation();
    // if (!Taro.getStorageSync('location_init')) {
    //   const res = await Taro.request({
    //     url: 'https://restapi.amap.com/v3/place/around?parameters',
    //     data: {
    //       key: 'b0121f143057c2f0c3607e48fe21bac9',
    //       location: '113.678280,23.628439',
    //       keywords: '医院',
    //     }
    //   })
    //   debugger;
    //   // TODO，post to backend
    //   if (res && res.data && res.data.pois) {
    //     const addRes = await axios.post('/city/cityMap', res.data.pois)
    //     if (addRes && addRes.data) {
          
    //     }
    //   }
    // }
    initHospital();
  })

  const onHandleError = (e) => {
    console.log(e, 'error');
  }

  const initHospital = async () => {
    const res = await axios.get('/hospital/getHospitals', {
      params: {
        // lon, 
        // la
      }
    })
    if (res && res.data) {
      setVisible(true);
      setList(res.data);
    }
  }

  const onChangeSearch = async (e) => {
    // e 的值返回的是一个数组，列如：[0, 0, 0]
    setSelectArea(Number(e.detail.value));
    const addr: string = areaList[Number(e.detail.value)]
    const arr = addr.split('-');
    setLocation(arr.join(' '));
    const province = cityMap.find((v: any) => v.name === arr[0]);
    if (province) {
      // @ts-ignore
      const city = province.cityVOS.find((v: any) => v.name === arr[1]);
      if (city) {
        // @ts-ignore
        const district = city.districts.find((v: any) => v.district === arr[2]);
        // initHospital(district.lon, district.la);
        setLatitude(district.la);
        setLongitude(district.lon);
      }
    }
  }

  const onClickDetail = (item) => {
    setDetailVisible(true);
    setDetail(item);
  }

  const onCloseDetail = () => {
    setDetailVisible(false);
    setDetail(null);
  }

  const onCommentInputChange = (e) => {
    setComment(e.detail.value);
  }

  const onClickComment = async () => {
    if (!comment) {
      Taro.showToast({
        title: '请输入评论',
        icon: 'error'
      })
      return;
    }
    const rate = Math.floor((Math.random() * 5));
    const res = await axios.post('/hospital/insertHospitalComment', {
      hospitalId: detail.id,
      content: comment,
      rate,
    })
    if (res && res.data) {
      setComment('');
      const commentRes = await axios.get('/hospital/getCommentByHosId', {
        params: {
          id: detail.id,
        }
      })
      if (commentRes && commentRes.data) {
        detail.comments = commentRes.data;
        setDetail({...detail});
      }
    }
  }

  return (
    <View className='page relative h-full' style={{ paddingTop: 64 }}>
      <View className='w-full text-center'>
        <Text className='text-[40px]'>
          疫苗先知
        </Text>
      </View>
      <View className=''>
        {/* <Picker
          className='flex flex-row items-center'
          mode="selector"
          range={areaList}
          value={selectArea}
          onChange={onChangeSearch}
        > */}
          <View className='flex flex-row items-center'>
            <Image className='w-[42px] h-[42px]' src={location === '定位' ? require('./images/location.png') : require('./images/location1.png')} />
            <Text>{location}</Text>
          </View>
          {/* <View className='flex flex-row items-center flex-1 relative px-2'>
            <Image src={require('./images/search.png')} className='w-[36px] h-[36px] absolute left-5 top-2' />
          </View> */}
        {/* </Picker> */}
      </View>
      <Map id="map" className='w-full h-[600px] mt-4' longitude={longitude} latitude={latitude} onError={onHandleError} />
      {
        visible &&
        <View className='fixed z-10 bottom-[186px] left-0 right-0 h-[600px] bg-white p-3 overflow-y-scroll'>
          <View className='text-[#333] text-center text-[40px] font-semibold'>附近医院</View>
          <View className='mt-4'>
            {
              list.map((item, index) => {
                return (
                  <View key={index} className='p-2 bg-[#EEEEEE] rounded-[16px] mb-6' onClick={() => onClickDetail(item)}>
                    <View className='flex flex-row items-center' key={index}>
                      <Image className='w-[140px] h-[140px] rounded-[20px]' src={item?.img} />
                      <View className='ml-3 flex-1'>
                        <View className='text-[#333] text-[30px]'>{item.name}</View>
                        <View className='text-[#A8A5A5] text-[24px] mt-2'>{item.address}</View>
                      </View>
                    </View>
                    <View className='text-right mt-0'>
                      <Text className='text-[#5959F8] text-28px[]'>医院评论{item.comments ? `(${item.comments.length})` : ''}</Text>
                    </View>
                  </View>
                )
              })
            }
            <View className='mt-4 text-center text-[#A8A5A5] text-[36px]'>没有更多了~</View>
          </View>
        </View>
      }
      {
        detailVisible && detail && 
        <View className='fixed z-10 bottom-[186px] left-0 right-0 top-[260px] bg-[#FAFAFA] flex flex-col pb-[2px]'>
          <View className=' overflow-y-scroll flex-1 pb-5 px-3 pt3'>
            <View className='bg-white py-3 px-4 relative'>
              <Image src={require('./images/close.png')} className='absolute top-3 right-3 w-[30px] h-[30px]' onClick={onCloseDetail} />
              <View>{detail?.name}</View>
              <View>{detail?.introduce}</View>
              {/* <View className='flex flex-row items-center'>
                <Text className='text-[#9292FC] text-[28px] px-4 py-2 rounded-md'>三级甲等</Text>
                <Text className='ml-3 text-[#9292FC] text-[28px] px-4 py-2 rounded-md'>医保</Text>
              </View> */}
              <View className='mt-3 text-[#333] text-[28px] line-clamp-3'>{detail?.desc}</View>
              <View className='mt-3 flex flex-row items-center justify-between'>
                <View className='flex flex-row items-center'>
                  <Image className='w-[40px] h-[40px]' src={require('./images/addr.png')} />
                  <Text className='text-[#333] text-[28px]'>地址</Text>
                </View>
                <View>
                  <Text className='text-[#999] text-[28px]'>{detail?.address}</Text>
                </View>
              </View>
              <View className='mt-3 flex flex-row items-center justify-between'>
                <View className='flex flex-row items-center'>
                  <Image className='w-[40px] h-[40px]' src={require('./images/call.png')} />
                  <Text className='text-[#333] text-[28px]'>联系电话</Text>
                </View>
                <View>
                  <Text className='text-[#999] text-[28px]'>{detail.phone}</Text>
                </View>
              </View>
            </View>
            <View className='bg-white py-3 px-4 mt-5' >
              {
                // 评论列表
                (detail.comments || []).map((item: any, i) => {
                  return (
                    <View key={i}>
                      <View className='flex flex-row items-center justify-between mt-3'>
                        <View className='flex flex-row items-center'>
                          <Image className='w-[120px] h-[120px] rounded-[60px] overflow-hidden bg-success' src={item?.imgUrl || require('./images/avatar.png')} />
                          <Text className='text-[#333] ml-4'>{item?.userNickName || '测试用户'}</Text>
                        </View>
                        {/* <View>优质评论</View> */}
                      </View>
                      <View className='text-[#333] text-[32px] line-clamp-3 mt-2'>{item.content}</View>
                      <View className='flex flex-row items-center'>
                        <Text className='text-[#999] text-[28px]'>{item.createTime}</Text>
                        {/* <Text className='text-[#999] text-[28px]'>查看</Text> */}
                      </View>
                    </View>
                  )
                })
              }
            </View>
          </View>
          <View className='h-[80px] flex flex-row items-center justify-between border border-solid border-[#eee]'
          style={{
            borderBottom: '1px solid #E5E6EB'
          }}>
            <Input 
              placeholder='请输入' 
              className='bg-white flex-1 h-[80px] px-3 border-[#E5E6EB]'
              value={comment} 
              onInput={onCommentInputChange}
              />
            <View className='bg-[#5959F8] text-white text-[32px] px-4 py-2 rounded-md' onClick={onClickComment}>评论</View>
          </View>
        </View>
      }
    </View>
  )
}
